/**
 * Created by wtfssd on 2017/9/13.
 */

import {Actions, ActionConst} from 'react-native-router-flux'

import * as request from '../utils/request'
import {AsyncStorage} from 'react-native'
import {Toast} from 'antd-mobile'
import {ERROR_MSG_DURATION} from '../utils/constant'

import JPush from '../push'

const STORAGE_KEY = "STORAGE_KEY_HOME";
const model = {
    namespace: 'auth',

    state: {
        isSignIn: false,
        sending: false,
        loading: false,
        sendButtonText: '获取验证码',
        coldDownTime: 60,
        profile: {
            member_id: null,
            avatar: null,
            user_name: null,
            phone: null
        },
        //{id: '1', name: '姓名！', phone: '13xxxxx1234', address: '湖北省武汉市硚口区 凯景国际大厦-古田二路凯景国际大厦'}
        addressList: [],
        productFavList: [],
        storeFavList: [],
        defaultAddress: null,
        coupon:0,
        integral:0
    },

    reducers: {
        save(state, {payload}) {
            return {...state, ...payload}
        }
    },

    effects: {
        //登陆
        * signIn({payload}, {call, put, select}) {
            console.log('auth effects signIn');
            const auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {loading: true}
            });
            const ddd = yield call(request.post, request.API.signIn, payload);
            if (!ddd || typeof ddd === 'undefined') {
                yield put({
                    type: 'save',
                    payload: {loading: false, profile: null, isSignIn: false}
                });
                yield put({
                    type: 'saveUserToStorage',
                    payload: {...auth}
                });
            } else {
                const data = ddd.data;
                JPush.setAlias(data.id);
                const profile = {...data, member_id: data.id, user_name: data.username};
                yield put({
                    type: 'save',
                    payload: {
                        loading: false,
                        isSignIn: true,
                        profile
                    }
                });
                const _auth = yield select(state => state.auth);
                yield put({
                    type: 'saveUserToStorage',
                    payload: {..._auth}
                });
                Toast.success('登录成功!', ERROR_MSG_DURATION);
                yield call(Actions.pop);
                if (payload.from) {
                    yield call(Actions.refresh, payload.from);
                }
            }


        },
        //注册
        * signUp({payload}, {call, put, select}) {

            const auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {loading: true}
            });
            const data = yield call(request.post, request.API.signUp, payload);
            if (!data || typeof data === 'undefined') {
                yield put({
                    type: 'save',
                    payload: {loading: false}
                });
                return;
            }


            Toast.success('注册成功!', ERROR_MSG_DURATION);
            yield call(Actions.pop);

        },
        //登出
        * signOut({payload}, {call, put, select}) {
            yield put({
                type: 'save',
                payload: {
                    isSignIn: false,
                    profile: null,
                    loading: false,
                    addressList: [],
                    productFavList: [],
                    defaultAddress: null
                }
            });
            const auth = yield select(state => state.auth);
            yield put({
                type: 'saveUserToStorage',
                payload: {...auth}
            });

        },


        //TODO:获取用户信息
        * fetchUserInfo({payload}, {call, put}) {

        },

        //修改密码
        * changePwd({payload}, {call, put, select}) {
            // console.log('auth effects changePwd');
            const data = yield call(request.post, request.API.changePwd, payload);
            if (!data || typeof data === 'undefined') return;
            yield put({
                type: 'signOut'
            });
            Toast.success('修改成功！请重新登录', ERROR_MSG_DURATION);
            yield call(Actions.pop);
        },


        //修改应户名
        * changeUserName({payload}, {call, put, select}) {
            const data = yield call(request.post, request.API.changeUserName, payload);

            if (!data || typeof  data === 'undefined') return;
            let auth = yield select(state => state.auth);


            let _profile = {...auth.profile};

            delete payload.phone;

            Object.keys(payload).map(k => {

                if (k === 'username') {
                    _profile['user_name'] = payload[k];
                } else {
                    _profile[k] = payload[k];
                }
            });
            yield put({
                type: 'save',
                payload: {profile: {..._profile}}
            });
            yield put({
                type: 'save',
                payload: {profile: {..._profile}}
            });
            auth = yield select(state => state.auth);
            yield put({
                type: 'saveUserToStorage',
                payload: {...auth}
            });
            yield call(Actions.pop);
        },
        //发送验证码
        * sendSms({payload}, {call, put, select}) {

            const auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {sending: true}
            });
            const data = yield call(request.post, request.API.sms, payload);
            yield put({
                type: 'save',
                payload: {sending: false}
            });
            if (!data || typeof data === 'undefined') {
                yield put({
                    type: 'clearTimer',
                });
                return;
            }
            Toast.success('验证码已成功发送请注意查收', ERROR_MSG_DURATION);
        },
        //添加收货地址
        * addAddress({payload}, {call, put, select}) {

            let auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {
                    loading: true
                }
            });
            const data = yield call(request.post, request.API.addressAdd, payload);
            yield put({
                type: 'save',
                payload: {
                    loading: false
                }
            });
            if (!data || typeof data === 'undefined') return;

            Toast.success('操作成功', ERROR_MSG_DURATION);
            yield put({
                type: 'fetchAddressList',
                payload,
            })

        },
        //获取地址列表
        * fetchAddressList({payload}, {call, put, select}) {

            let auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {
                    loading: true
                }
            });
            const data = yield call(request.post, request.API.addressList, payload);

            yield put({
                type: 'save',
                payload: {
                    loading: false
                }
            });
            if (!data || typeof data === 'undefined') return;

            let addressList = [];
            let defaultAddress = null;
            if (Array.isArray(data.data)) {
                data.data.map((i) => {
                    if (i.default_address === 1) {
                        defaultAddress = i;
                    }
                });
                addressList = data.data;
            }

            yield put({
                type: 'save',
                payload: {
                    addressList,
                    defaultAddress,
                }
            });
            yield put({
                type: 'saveUserToStorage',
                payload: {...auth}
            });
        },
        //删除收货地址
        * addressDelete({payload}, {call, put, select}) {

            let auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {
                    loading: true
                }
            });
            const data = yield call(request.post, request.API.addressDelete, payload);
            console.log(data, payload);
            yield put({
                type: 'save',
                payload: {
                    loading: false
                }
            });
            if (!data || typeof data === 'undefined') return;
            yield put({
                type: 'fetchAddressList',
                payload: {
                    user_id: payload.user_id
                }
            });
            Toast.success('操作成功', ERROR_MSG_DURATION);
        },


        //获取商品收藏列表
        * fetchFavList({payload}, {call, put, select}) {
            const auth = yield select(state => state.auth);
            if (!auth.isSignIn) return;
            yield put({
                type: 'save',
                payload: {loading: true}
            });
            payload['id'] = auth.profile.member_id;
            const data = yield call(request.post, request.API.productFavList, payload);
            yield put({
                type: 'save',
                payload: {loading: false},
            });
            if (!data || typeof data === 'undefined') return;

            console.log('收藏商品列表', data);
            yield put({
                type: 'save',
                payload: {loading: false, productFavList: data.data}
            })
        },
        //获取店铺收藏列表
        * fetchStoreFavList({payload}, {call, put, select}) {
            const auth = yield select(state => state.auth);
            if (!auth.isSignIn) return;
            yield put({type: 'save', payload: {loading: true}});
            payload['user_id'] = auth.profile.member_id;
            const data = yield call(request.post, request.API.storeFavList, payload);
            yield put({type: 'save', payload: {loading: false},});
            if (!data || typeof data === 'undefined') return;
            yield put({type: 'save', payload: {storeFavList: data.data}});
            console.log('店铺收藏', data);
        },


        * clearTimer({payload}, {put, select}) {

            const auth = yield select(state => state.auth);
            yield put({
                type: 'save',
                payload: {timer: null, sending: false, loading: false, sendButtonText: '获取验证码', coldDownTime: 60}
            })

        },
        //保存用户信息到本地存储
        * saveUserToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload))
        },
        //从本地存储中恢复用户信息
        * restoreUserFromStorage({payload}, {call, put, select}) {
            const profile = yield call(AsyncStorage.getItem, STORAGE_KEY);

            yield put({
                type: 'save',
                payload: {...JSON.parse(profile)}
            });
            let auth = yield select(state => state.auth);
            if (auth.isSignIn) {
                yield put({
                    type: 'fetchUserInfo',
                    payload: {id: auth.profile.member_id}
                });
                auth = yield select(state => state.auth);
                JPush.setAlias(auth.profile.member_id);
            }
        },
        * getCouponIntergral({payload}, {call, put, select}) {
            let auth = yield select(state => state.auth);
            if (!payload) payload = {};
            payload['user_id'] = auth.profile.member_id;
            const result = yield call(request.get, request.API.getCouponIntergral, payload);
            if(result&&typeof result!=='undefined'){
                auth.coupon = result.data.coupon;
                auth.integral = result.data.integral;
                yield put({
                    type:'save',
                    payload:{...auth}
                })
            }
        }

    },

    subscriptions: {
        setup({dispatch}) {
            //启动时从本地存储中恢复用户信息
            dispatch({
                type: 'restoreUserFromStorage',
            });
        }
    },
};

export default model